package org.jeecg.modules.exPingbiao.util;

import com.itextpdf.text.Document;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.*;
import org.jeecg.modules.exProject.entity.ExProject;
import org.jeecg.modules.exProject.entity.ExSection;

import java.io.*;
import java.text.NumberFormat;
import java.util.*;

/**
 * PDF操作工具类
 */
public class PDFUtils {

    /**
     * 生成评标报告pdf
     */
    public static String  generatePingBiaoExport(ExSection section, ConfigUtils config){
        // 模板文件路径
        String inputFileName = config.getTemplatePath();
        String resultFileName = UUID.randomUUID().toString() + ".pdf";
        // 生成的文件路径
        String outputFileName = config.getUploadfilepath() + resultFileName;

        OutputStream os = null;
        PdfStamper ps = null;
        PdfReader reader = null;
        PdfStamper stamper = null;

        try {
            os = new FileOutputStream(new File(outputFileName));
            // 2 读入pdf表单
            reader = new PdfReader(inputFileName);
            // 3 根据表单生成一个新的pdf
            ps = new PdfStamper(reader, os);
            // 4 获取pdf表单
            AcroFields form = ps.getAcroFields();
            form.setFieldProperty("", "textsize", new Float(12), null);
            // 5给表单添加中文字体
            BaseFont bf = BaseFont.createFont(config.getFontPath(), BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);

            form.addSubstitutionFont(bf);
            // 6查询数据================================================
            Map<String, Object> data = new HashMap<String, Object>();
            data.put("projectName", section.getProjectName());
            data.put("projectCode", section.getProjectCode());
            data.put("sectionCode", section.getBidSectionCode());
            data.put("sectionName", section.getBidSectionName());

            Calendar cal = Calendar.getInstance();
            cal.setTime(new Date());

            data.put("year", cal.get(Calendar.YEAR));
            data.put("month",cal.get(Calendar.MONTH) + 1);
            data.put("day", cal.get(Calendar.DATE));
            // 7遍历data 给pdf表单表格赋值
            for (String key : data.keySet()) {
                form.setField(key, data.get(key).toString());
            }
            ps.setFormFlattening(true);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                ps.close();
                reader.close();
                os.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return resultFileName;
    }

    /**
     * 生成协议并电子签章
     */
    public static String  generateAgreement(ExSection section,ConfigUtils config){
        // 模板文件路径
        String inputFileName = config.getTemplatePath();
        String resultFileName = UUID.randomUUID().toString() + ".pdf";
        // 生成的文件路径
        String outputFileName = config.getUploadfilepath() + resultFileName;

        OutputStream os = null;
        PdfStamper ps = null;
        PdfReader reader = null;
        PdfStamper stamper = null;

        try {
            os = new FileOutputStream(new File(outputFileName));
            // 2 读入pdf表单
            reader = new PdfReader(inputFileName);
            // 3 根据表单生成一个新的pdf
            ps = new PdfStamper(reader, os);
            // 4 获取pdf表单
            AcroFields form = ps.getAcroFields();
            form.setFieldProperty("", "textsize", new Float(12), null);
            // 5给表单添加中文字体
            BaseFont bf = BaseFont.createFont(config.getFontPath(), BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);

            form.addSubstitutionFont(bf);
            // 6查询数据================================================
            Map<String, Object> data = new HashMap<String, Object>();
            data.put("projectName", section.getProjectName());
            data.put("projectCode", section.getProjectCode());
            data.put("sectionCode", section.getBidSectionCode());
            data.put("sectionName", section.getBidSectionName());
            data.put("tenderBondRMB", upperCase2(section.getAmount().doubleValue()));
            data.put("feeRMB", upperCase2(section.getAmount().doubleValue()));

            // 7遍历data 给pdf表单表格赋值
            for (String key : data.keySet()) {
                form.setField(key, data.get(key).toString());
            }
            ps.setFormFlattening(true);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                ps.close();
                reader.close();
                os.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        //电子签章
        Document document=null;
        PdfStamper stamper2=null;
        try {
            // 读取模板文件
            InputStream input = new FileInputStream(new File(outputFileName));
            reader = new PdfReader(input);
            //获取页数
            int pagecount= reader.getNumberOfPages();
            // 生成的文件路径
            String outSealFileName = config.getUploadfilepath() + resultFileName;

            stamper2 = new PdfStamper(reader, new FileOutputStream(
                    outSealFileName));


            document = new Document(reader.getPageSize(1));

            // 获取页面宽度
            float width = document.getPageSize().getWidth();
            // 获取页面高度
            float height = document.getPageSize().getHeight();
            // 读图片
            Image image = Image.getInstance("1111111111111111111111111.jpg"); // 获取公章
            // 根据域的大小缩放图片
            image.scaleToFit(150, 150);
            image.setAbsolutePosition((width-150)/2, (height-150)/2);
            // 获取操作的页面　　根据pagecount给pdf最后一页添加签章
            for (int i = 1; i <= pagecount ; i++){
                PdfContentByte under = stamper2.getOverContent(i);
                // 添加图片
                under.addImage(image);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(document!=null){
                document.close();
            }
            if(stamper2!=null) {
                try {
                    stamper2.close();
                }catch (Exception e1){
                    e1.printStackTrace();
                }
            }
            if(reader!=null) {
                reader.close();
            }
        }
        return resultFileName;
    }

    public static   String upperCase2(double money){
        String[] upNum = {"零","壹","贰","叁","肆","伍","陆","柒","捌","玖"};
        String[] danwei = {"圆","拾","佰","仟","万","拾","佰","仟","亿","拾","佰","仟"};
        //取消科学记数法
        NumberFormat numFormat = NumberFormat.getInstance();
        numFormat.setMaximumFractionDigits(2);//设置小数位个数
        numFormat.setGroupingUsed(false);//取消科学技术发
        String formatNum = numFormat.format(money);
        String strmoney = formatNum + "";//浮点型转为字符型
        String lastUpNum = "null"; //用于存放上个参数的值
        String result = "";//返回的结果
        String[] split = strmoney.split("\\.");
        String strMoney = split[0];
        String point = "";
        //小数部分取值处理。
        if(split.length>1){
            point = split[1];
            if(point.length()==1){
                point = point.concat("0");
            }
        }else {
            point = "0";
        }
        //大于12位就直接返回。
        int moneyLen = strMoney.length();
        if(money==0){
            return "零圆整";
        }
        if(moneyLen>12){
            return "金额："+money+"元，超出大写转换范围。最大金额：999999999999.99元";
        }
        //整数(integer)部分处理。
        if(!"0".equals(strMoney)){
            for (int i = 0; i < moneyLen; i++) {
                String strNum = strMoney.charAt(i)+"";
                int singleNum = Integer.parseInt(strNum);
                String upSingleNum = upNum[singleNum];
                //上一为不等于0的情况
                if(!"零".equals(lastUpNum)){
                    if(!"零".equals(upSingleNum)){
                        result = result.concat(upSingleNum).concat(danwei[moneyLen-i-1]);
                    }else
                        //为零但是在万、亿位上要加单位 (moneyLen-i)==9 指的是单位：亿。  (moneyLen-i)==5指的是单位：万
                        if( (moneyLen-i)==5 || (moneyLen-i)==9 ){
                            lastUpNum="";
                        }else {
                            result=result.concat(upSingleNum);
                        }
                }
                //上一位为0的情况
                if("零".equals(lastUpNum) && !"零".equals(upSingleNum)){
                    result = result.concat(upSingleNum).concat(danwei[moneyLen-i-1]);
                }
                //捕捉上一位数（lastUpNum）为零的情况做优化。
                if((moneyLen-i)==5 || (moneyLen-i)==9 ){
                    //排除加单位时前面为"零"的情况。如：两百零万
                    if("零".equals(lastUpNum)||"null".equals(lastUpNum)){
                        result = result.substring(0,result.length()-1);
                    }
                    if(!result.endsWith("亿")){
                        result = result.concat(danwei[moneyLen-i-1]);
                    }
                    lastUpNum="";
                }else {
                    //把当前大写数字复制给 lastUpNum 用于下次判断
                    lastUpNum = upSingleNum;
                }
            }
            //对几万元整和几亿元整(result:五万零或者五亿零零)做优化。
            result=result.replaceAll("零零","零");
            if(result.endsWith("零")){
                String substring = result.substring(0,result.length() - 1);
                result = substring;
            }
            result = result.concat("圆");
            result = result.replaceAll("圆圆","圆");
            result = result.replaceAll("万万","万");

        }

        //小数(point)部分处理
        if("0".equals(point)){
            result =  result+"整";
        }else {
            //去 整
//            if(result.endsWith("整")){
//                result = result.substring(0,result.length()-1);
//            }
            if((point.charAt(0)+"").equals("0")){
                result = result.concat(upNum[Integer.parseInt(point.charAt(1)+"")]+"分");
            }else if((point.charAt(1)+"").equals("0")){
                result = result.concat(upNum[Integer.parseInt(point.charAt(0)+"")]+"角");
            }else {
                result = result.concat(upNum[Integer.parseInt(point.charAt(0)+"")]+"角").concat(upNum[Integer.parseInt(point.charAt(1)+"")]+"分");
            }
        }
        return result;
    }


}
